﻿using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse.AI.Group;
using Verse;

namespace RimZombieGirl
{
    public class IncidentDefExtension_BurrowingInsects : DefModExtension
    {
        public IntRange insectCount = new IntRange(3, 6);
        public List<PawnKindDef> insectKinds;
    }

    public class IncidentWorker_BurrowingInsects : IncidentWorker
    {
        protected override bool CanFireNowSub(IncidentParms parms)
        {
            return base.CanFireNowSub(parms) && parms.target is Map;
        }

        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map map = (Map)parms.target;
            if (map == null) return false;

            IncidentDefExtension_BurrowingInsects ext = def.GetModExtension<IncidentDefExtension_BurrowingInsects>();
            if (ext == null || ext.insectKinds.NullOrEmpty())
            {
                Log.Error($"IncidentDef {def.defName} 缺少 IncidentDefExtension_BurrowingInsects 配置！");
                return false;
            }

            List<Thing> corpses = map.listerThings.ThingsInGroup(ThingRequestGroup.Corpse)
                .Where(c => c is Corpse corpse && corpse.InnerPawn != null).ToList();

            //生成数量
            int count = ext.insectCount.RandomInRange;

            List<Pawn> spawned = new List<Pawn>();
            for (int i = 0; i < count; i++)
            {
                IntVec3 spawnCell;

                if (corpses.Any() && Rand.Chance(0.8f)) //80%概率在尸体位置
                {
                    Corpse chosenCorpse = corpses.RandomElement() as Corpse;
                    spawnCell = chosenCorpse.Position;

                    //不会再次选中
                    corpses.Remove(chosenCorpse);
                }
                else
                {
                    if (!CellFinderLoose.TryFindRandomNotEdgeCellWith(
                            10,
                            c => c.Standable(map),
                            map,
                            out spawnCell))
                    {
                        continue;
                    }
                }

                // 随机一个虫子种类
                PawnKindDef kind = ext.insectKinds.RandomElement();
                Faction faction = Find.FactionManager.FirstFactionOfDef(FactionDef.Named("RI_Faction_Aberrant"));
                Pawn insect = PawnGenerator.GeneratePawn(kind, faction);               

                //生成时让虫子饥饿
                if (insect.needs?.food != null)
                {
                    insect.needs.food.CurLevel = 0f;
                }
                GenSpawn.Spawn(insect, spawnCell, map, WipeMode.Vanish);

                spawned.Add(insect);
            }


            if (spawned.Any())
            {
                LordJob lordJob = new LordJob_DefendPoint(spawned.First().Position);
                LordMaker.MakeNewLord(Faction.OfInsects, lordJob, map, spawned);

                string label = def.letterLabel;
                string text = def.letterText;
                SendStandardLetter(label, text, def.letterDef, parms, spawned);
                return true;
            }

            return false;
        }
    }
}
